<?php
namespace app\shop\service\company;
use app\shop\model\company\Interview as InterviewModel;
use app\shop\model\company\InterviewLog;
use app\shop\validate\company\Interview as InterviewValidate;
use app\shop\model\company\Company as CompanyModel;
use app\common\service\Result;
use Dompdf\Dompdf;
class Interview
{
    public function list($data)
    {
        try {
            $app_id = request()->app_id;
            $map = [
                ['app_id', '=', $app_id]
            ];

            $page_size = $data['page_size'] ?? 20;
            if (isset($data['department_id']) && $data['department_id'] > 0) {
                $map[] = ['department_id', '=', $data['department_id']];
            }
            if (isset($data['station_id']) && $data['station_id'] > 0) {
                $map[] = ['station_id', '=', $data['station_id']];
            }
            if (isset($data['result']) && $data['result']) {
                $map[] = ['result', 'in', $data['result']];
            }
            $query = InterviewModel::with([
                'station' => function ($query) {
                    return $query->field('id,title');
                },
                'department' => function ($query) {
                    return $query->field('id,title');
                }
            ]);
            if (isset($data['username']) && $data['username']) {
                $query->where('name|mobile', 'like', "%" . $data['username'] . "%");
            }
            $lists = $query->where($map)->order('status desc, order_time,id')->append(['result_text'])->paginate($page_size);
            $lists->each(function ($item, $key) {
                //当前轮次面试官
                $item['interviewer'] = InterviewLog::where('interview_id', $item['id'])->order('round desc')->with('user')->find();
            });
            return Result::success($lists);
        } catch (\Exception $e) {
            return Result::error($e->getMessage());
        }
    }

    public function info($id)
    {
        try {
            $app_id = request()->app_id;
            $info = InterviewModel::where('app_id', $app_id)->with([
                'logs' => function ($query) {
                    return $query->with('user')->append(['result_text']);
                },
                'department',
                'station'
            ])->append(['result_text'])->find($id);
            //当前面试官
            $interviewer = $info['logs'][count($info['logs']) - 1]['user'] ?? [];
            $info['interviewer_name'] = $interviewer['real_name'] ?? "";
            $info['interviewer'] = $interviewer['user_id'] ?? 0;
            return Result::Success($info);
        } catch (\Exception $e) {
            return Result::error($e->getMessage());
        }
    }

    public function form($id)
    {
        $app_id = request()->app_id;
        $info = InterviewModel::where('app_id', $app_id)->field('id,department_id,station_id,name,mobile,order_time,file')->find($id);
        //当前面试官
        $interviewer = InterviewLog::where('interview_id', $id)->order('round desc')->value('interviewer');
        $info['interviewer'] = $interviewer;
        return Result::Success($info);
    }

    //添加部门成员
    public function save($data)
    {
        try {
            $app_id = request()->app_id;
            $id = $data['id'] ?? 0;
            //是否已存在
            if ($id) {
                $info = InterviewModel::where('app_id', $app_id)->find($id);
                if (!$info) {
                    return Result::error('数据不存在');
                }
                $info->save($data);
            } else {
                unset($data['id']);
                $data['app_id'] = $app_id;
                $data['add_user'] = $data['add_user'] ?? 0;
                $info = InterviewModel::create($data);
            }
            if ($data['interviewer']) {       //选择了面试官，增加第一轮面试
                $log = InterviewLog::where('interview_id', $info->id)->order('round desc')->find();
                if (!$log) {
                    $log = InterviewLog::create([
                        'interview_id' => $info->id,
                        'interviewer' => $data['interviewer'],
                    ]);
                } else {
                    $log->interviewer = $data['interviewer'];
                    $log->save();
                }
            }
            return Result::success();
        } catch (\Exception $e) {
            return Result::error($e->getMessage());
        }
    }

    //删除部门成员
    public function delete($id)
    {
        try {
            $app_id = request()->app_id;
            $info = InterviewModel::where('app_id', $app_id)->find($id);
            $info->delete();
            return Result::success();
        } catch (\Exception $e) {
            return Result::error($e->getMessage());
        }
    }

    public function logs($view_id)
    {
        try {
            $app_id = request()->app_id;
            $view = InterviewModel::where('app_id', $app_id)->find($view_id);
            if (!$view) {
                return Result::error('参数错误');
            }
            $map = [
                ['interview_id', '=', $view_id]
            ];
            $lists = InterviewLog::where($map)->with('user')->order('round desc')->append(['result_text'])->select();
            return Result::success($lists);
        } catch (\Exception $e) {
            return Result::error($e->getMessage());
        }
    }

    public function saveLog($data)
    {
        try {
            validate(InterviewValidate::class)->scene('saveLog')->check($data);
            $app_id = request()->app_id;
            $log = InterviewLog::find($data['id']);
            if (!$log) {
                return Result::error('记录不存在');
            }
            if ($log->interviewer != request()->user_id) {
                return Result::error('您不是当前面试官');
            }
            $interview = InterviewModel::where('app_id', $app_id)->find($log->interview_id);
            if (!$interview || $interview->getData('result') != 0) {
                return Result::error('面试信息不存在');
            }
            $log->save($data);
            $interview->status = $log->round;
            $next = $data['next'];
            if ($data['result'] == 1) {
                if ($next) {
                    //新增一轮面试
                    InterviewLog::create([
                        'interview_id' => $interview->id,
                        'round' => $log->round + 1,
                    ]);
                    $interview->status = $log->round + 1;
                } else {
                    $interview->result = 1;
                }
            } elseif ($data['result'] == 2) {
                $interview->result = 2;
            }
            $interview->save();
            return Result::success([]);
        } catch (\Exception $e) {
            return Result::error($e->getMessage());
        }
    }
    public function offer($id)
    {
        try {
            $info = InterviewModel::with(['department', 'station'])->find($id);
            if ($info['result'] != 1 && $info['result'] != 3) {
                return Result::error('状态错误');
            }
            //生成offer文件pdf
            $dompdf = new Dompdf([
                'isRemoteEnabled' => true,
                'isPhpEnabled' => true,
                'defaultFont' => 'stsong', // 支持中文的字体
            ]);
            $company = CompanyModel::find(request()->app_id);
            $tpl_data = [
                'name' => $info['name'],
                'department' => $info['department']['title'],
                'station' => $info['station']['title'],
                'company_name' => $company['title'],
                'offer_date' => date("Y-m-d"),
            ];
            $templateContent = file_get_contents(app()->getRootPath() . 'public/tpl/pdf/offer.html');
            // 填充数据到模板
            foreach ($tpl_data as $key => $value) {
                $templateContent = str_replace('{{' . $key . '}}', htmlspecialchars($value, ENT_QUOTES, 'UTF-8'), $templateContent);
            }
            $dompdf->loadHtml($templateContent, 'UTF-8');
            $dompdf->setPaper('A4', 'portrait');
            $dompdf->render();
            $file_path = app()->getRootPath() . 'public/download/offer_letters/';
            if (!is_dir($file_path)) {
                mkdir($file_path, 0777, true);
            }
            $file_name = $info['name'] . '_offer_letter.pdf';
            $outputPath = $file_path . $file_name;
            file_put_contents($outputPath, $dompdf->output());
            // 返回成功结果
            $file_url = config('app.file_domain') . '/download/offer_letters/' . $file_name;
            $info->offer = $file_url;
            $info->result = 3;
            $info->save();
            return Result::success($file_url);
        } catch (\Exception $e) {
            return Result::error($e->getMessage());
        }
    }
}